package GDoc::Job::Fetch::US::Exec::EOP::CEA::ERPData;

use Moose;

use WWW::Mechanize;
use GDoc::Job;
use File::Temp;


extends 'GDoc::Job::Fetch::US::Exec::EOP';

sub setup {
    my $self = shift;
    $self->_baseurl( 'http://www.gpoaccess.gov/eop/tables%02d.html' );
    $self->_basedir( 'http://www.gpoaccess.gov/eop/' );
}

sub run { 
    my $self = shift;
   
    if ( $self->data->{link} ) { 
        $self->_fetch_xls;
    } else { 
        foreach my $year ( 1 .. 9 ) { 
            my $url = sprintf( $self->_baseurl, $year );
            $self->logger->info( "fetching base $url" );

            my $mech = $self->_mech;
            $mech->get( $url );
            my @links = $mech->find_all_links( url_regex => qr{B\d{1,3}\.xls$}i );

            foreach my $link( @links ) { 
                $link->text =~ m{B-(?<num>\d{1,3})\.\s+(?<title>.+?)$};
                my ( $num, $title ) = @+{ 'num', 'title' };

                my $job = GDoc::Job->new( class => 'Fetch::US::Exec::EOP::CEA::ERPData',
                                          queue => $self->fetch_queue,
                                          data  => { link    => $link->url,
                                                     year    => ( $year + 2000 ),
                                                     num     => $num,
                                                     title   => $title
                                                   }
                                        );
                
                $job->submit;
            }
        }
    }
}


sub _fetch_xls { 
    my $self = shift;
    my %data = %{ $self->data };

    my $url = $data{link} =~ m{^http://} ? $data{link} : $self->_basedir . $data{link};
    
    my $ident = sprintf( 'CEA-ERPB-%04d-%03d', $data{year}, $data{num} );
    my $filename = $ident . '.xls';
    my $key = 'us/exec/eop/cea/' . $filename;

    my $bkt = $self->s3->bucket( $self->docs_bucket );
    if ( $bkt->head_key( $key ) ) { 
        $self->logger->info( "Already have $url, skipping" );
        return;
    }

    $self->logger->info( "Storing $url --> $key" );

    my $mech = $self->_mech;
    $mech->get( $url );

    $self->store_xls( key       => $key,
                      data      => $mech->response->content,
                      filename  => $filename,
                      meta      => { description  => $data{title},
                                     identifier   => $ident
                                   }
                    );               
}

1;
